﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using DP.Web.UI;
using System.Reflection;
using DP.Common;

namespace CRM.Web.ConsultingCaseManage
{
    public partial class Modify : Common.PageBase
    {
        /// <summary>
        /// Gets or sets the case status.
        /// </summary>
        /// <value>
        /// The case status.
        /// </value>
        private string CaseStatus
        {
            get { return (ViewState["CaseStatus"] == null) ? "" : ViewState["CaseStatus"].ToString(); }
            set { ViewState["CaseStatus"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        T_CONSULTINGCASE_BLL bll = new T_CONSULTINGCASE_BLL();
        /// <summary>
        /// 
        /// </summary>
        T_WORKORDERSTATUS_BLL workOrderStatusBll = new T_WORKORDERSTATUS_BLL();
        /// <summary>
        /// 
        /// </summary>
        private T_WORKORDEROPERATION_BLL workOrderOperationBll = new T_WORKORDEROPERATION_BLL();
        /// <summary>
        /// 
        /// </summary>
        private T_WORKORDERLOG_BLL workOrderLogBll = new T_WORKORDERLOG_BLL();
        /// <summary>
        /// 数据字典
        /// </summary>
        T_DICTIONARY_BLL dictionaryBll = new T_DICTIONARY_BLL();


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            if (PageHelper.GetQueryString(this.Page, "PageTarget") != "Opener")
            {
                PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
                btnCancel.Attributes["onclick"] = UserLoginInfo.FilterBackUrl(btnCancel.Attributes["onclick"]);
            }
            else
            {
                PageHelper.SetClose(this.Page, btnCancel);
                btnCancel.Value = "关 闭";
            }
            PageHelper.SetPopCalender(this.Page, txtCREATETIME);
            PageHelper.SetPopCalender(this.Page, txtLASTMODIFYTIME);


        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlCUSTOMERBASEBinding();
                ddlCUSTOMERTYPEBinding();
                ddlCUSTOMERLEVELBinding();
                ddlBIGCUSTOMERTYPEBinding();

                ddlSTATUSBinding();
                ddlCONSULTINGTYPEBinding();
                pageDataInit();
            }

            LoadButton();

        }

       

        #region 页面初始化数据绑定


        /// <summary>
        /// DDLs the CUSTOMERBASE binding.
        /// </summary>
        private void ddlCUSTOMERBASEBinding()
        {
            ddlCUSTOMERBASE.DataSource = dictionaryBll.GetCacheListByType(this.Page, DictionaryType.GetNameByKey("CustomerBase"));
            ddlCUSTOMERBASE.DataTextField = "DictValue";
            ddlCUSTOMERBASE.DataValueField = "DictKey";
            ddlCUSTOMERBASE.DataBind();
            ddlCUSTOMERBASE.Items.Insert(0, new ListItem("", ""));

        }

        /// <summary>
        /// DDLs the CUSTOMERTYPE binding.
        /// </summary>
        private void ddlCUSTOMERTYPEBinding()
        {
            ddlCUSTOMERTYPE.DataSource = dictionaryBll.GetCacheListByType(this.Page, DictionaryType.GetNameByKey("CustomerType"));
            ddlCUSTOMERTYPE.DataTextField = "DictValue";
            ddlCUSTOMERTYPE.DataValueField = "DictKey";
            ddlCUSTOMERTYPE.DataBind();
            ddlCUSTOMERTYPE.Items.Insert(0, new ListItem("", ""));

        }

        /// <summary>
        /// DDLs the CUSTOMERLEVEL binding.
        /// </summary>
        private void ddlCUSTOMERLEVELBinding()
        {
            ddlCUSTOMERLEVEL.DataSource = dictionaryBll.GetCacheListByType(this.Page, DictionaryType.GetNameByKey("CustomerLevel"));
            ddlCUSTOMERLEVEL.DataTextField = "DictValue";
            ddlCUSTOMERLEVEL.DataValueField = "DictKey";
            ddlCUSTOMERLEVEL.DataBind();
            ddlCUSTOMERLEVEL.Items.Insert(0, new ListItem("", ""));

        }

        /// <summary>
        /// DDLs the BIGCUSTOMERTYPE binding.
        /// </summary>
        private void ddlBIGCUSTOMERTYPEBinding()
        {
            ddlBIGCUSTOMERTYPE.DataSource = dictionaryBll.GetCacheListByType(this.Page, DictionaryType.GetNameByKey("BigCustomerType"));
            ddlBIGCUSTOMERTYPE.DataTextField = "DictValue";
            ddlBIGCUSTOMERTYPE.DataValueField = "DictKey";
            ddlBIGCUSTOMERTYPE.DataBind();
            ddlBIGCUSTOMERTYPE.Items.Insert(0, new ListItem("", ""));

        }


        /// <summary>
        /// DDLs the STATUS binding.
        /// </summary>
        private void ddlSTATUSBinding()
        {
            List<T_WORKORDERSTATUS_Entity> list = workOrderStatusBll.GetSessionList(this.Page,
                                                                                    ((int) WorkOrderType.咨询工单).ToString());

            ddlSTATUS.DataSource = list;
            ddlSTATUS.DataTextField = "OrderStatusName";
            ddlSTATUS.DataValueField = "OrderStatusID";
            ddlSTATUS.DataBind();
        }

        /// <summary>
        /// DDLs the CONSULTINGTYPE binding.
        /// </summary>
        private void ddlCONSULTINGTYPEBinding()
        {
            ddlCONSULTINGTYPE.DataSource = dictionaryBll.GetCacheListByType(this.Page, DictionaryType.GetNameByKey("ConsultingType"));
            ddlCONSULTINGTYPE.DataTextField = "DictValue";
            ddlCONSULTINGTYPE.DataValueField = "DictKey";
            ddlCONSULTINGTYPE.DataBind();
            ddlCONSULTINGTYPE.Items.Insert(0, new ListItem("", ""));

        }

        #endregion

        private void pageDataInit()
        {
            string _caseid = String.IsNullOrEmpty(Request.QueryString["CASEID"]) ? "" : Request.QueryString["CASEID"].Trim();

            if (!String.IsNullOrEmpty(_caseid))
            {
                T_CONSULTINGCASE_Entity entity = bll.GetEntity("CASEID", _caseid);

                PageHelper.SetControlValue<T_CONSULTINGCASE_Entity>(this.Page, entity);
                //PageHelper.SetControlEnabled(this.phBaseInfo, false);
                PageHelper.SetControlEnabled(this.phCreateInfo, false);
                
                CaseStatus = entity.STATUS.Trim();

                T_WORKORDERSTATUS_Entity workorderstatusEntity =
                                                workOrderStatusBll.GetPageItem_T_WORKORDERSTATUS_EntityByKey(this.Page, StringHelper.ToInt(entity.STATUS.Trim(), 0));
                
            }

        }

        /// <summary>
        /// 
        /// Loads the button.
        /// </summary>
        private void LoadButton()
        {
            List<T_WORKORDEROPERATION_Entity> workOrderOperationList = workOrderOperationBll.GetList(string.Format(" and CurrentStatusID = {0} and OrderTypeID = {1} ", CaseStatus, ((int)WorkOrderType.咨询工单).ToString()));
            foreach (var entity in workOrderOperationList)
            {
                Button btn = new Button();
                btn.ID = StaticConstant.PreConsultingCase + entity.OPERATIONID.ToString();
                btn.CommandName = StaticConstant.PreConsultingCase + entity.OPERATIONID.ToString();
                btn.Text = entity.OPERATIONNAME;
                btn.CssClass = "btn";
                //if (entity.ISCONFIRM.ToString() == ((int)IsConfirm.是).ToString())
                //{
                //    btn.OnClientClick = String.Format("return confirm('您确认要执行 {0} 操作吗？');", entity.OPERATIONNAME);
                //}
                btn.Click += new EventHandler(btnOK_Click);
                phButton.Controls.Add(btn);
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            string strUpdateContent = "";
            if (!(sender is Button)) return;
            Button btn = sender as Button;
            string operationId = btn.CommandName.Replace(StaticConstant.PreConsultingCase, "");
            T_WORKORDEROPERATION_Entity workOrderOperationEntity =
                workOrderOperationBll.GetCache_T_WORKORDEROPERATION_EntityByKey(this.Page,
                                                                                StringHelper.ToInt(operationId, 0));

            string _caseid = String.IsNullOrEmpty(Request.QueryString["CASEID"]) ? "" : Request.QueryString["CASEID"].Trim();
            T_CONSULTINGCASE_Entity entity = bll.GetEntity("CASEID", _caseid);
            if (entity == null)
            {
                return;
            }

            if (entity.STATUS.ToString() != workOrderOperationEntity.CURRENTSTATUSID.ToString())
            {
                PageHelper.ShowMessage(this.Page, "工单状态已被他人修改！", Request.RawUrl.ToString());
                return;
            }

            if ((IsUpdateInfo) Enum.Parse(typeof (IsUpdateInfo), workOrderOperationEntity.ISUPDATEINFO.ToString()) == IsUpdateInfo.是)
            {
                strUpdateContent = PageHelper.GetControlValue<T_CONSULTINGCASE_Entity>(this.Page, ref entity);
            }

            // 执行相关反射操作
            MethodResult result = new MethodResult();
            workOrderOperationBll.AssociatedAction<T_CONSULTINGCASE_Entity>(workOrderOperationEntity, entity, result);
            if (result.Result == MethodResult.ResultType.Failure)
            {
                PageHelper.ShowMessage(this.Page, result.Message);
                return;
            }

            entity.STATUS = workOrderOperationEntity.NEXTSTATUSID.ToString();

            entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
            entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
            entity.LASTMODIFYTIME = DateTime.Now;

            try
            {
                long rel = bll.Update(entity);
                if (rel > 0)
                {
                    #region 更新到中间表
                    if (workOrderStatusBll.GetSessionStatusType(this.Page, entity.STATUS) == StatusType.结束节点)
                    {
                        try
                        {
                            CC_CONSULTINGCASE_BLL ccBll = new CC_CONSULTINGCASE_BLL();
                            CC_CONSULTINGCASE_Entity ccEntity = new CC_CONSULTINGCASE_Entity();
                            ccBll._dal.ObjectCopyTo(entity, ccEntity);
                            ccBll.Delete("CASEID", entity.CASEID.ToString());
                            ccBll.Insert(ccEntity);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog("MiddleDataBase", String.Format("CaseID:{0}--Message:{1}", entity.CASEID.ToString(), ex.Message));

                        }
                    }
                    #endregion

                    #region 状态变更日志
                    try
                    {
                        if (configBll.GetCacheValueByName(this.Page, "WorkOrderLog").ToLower() != "False")
                        {
                            T_WORKORDERLOG_Entity workOrderLogEntity = new T_WORKORDERLOG_Entity();
                            workOrderLogBll._dal.ObjectCopyTo(workOrderOperationEntity, workOrderLogEntity);
                            workOrderLogEntity.CASEID = entity.CASEID;
                            workOrderLogEntity.CUSTOMERCODE = entity.CUSTOMERCODE;
                            workOrderLogEntity.CREATEPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                            workOrderLogEntity.CREATEPEOPLEID = _userLoginInfo.UserEntity.USERID;
                            workOrderLogEntity.CREATETIME = DateTime.Now;
                            workOrderLogEntity.UPDATECONTENT = strUpdateContent;
                            workOrderLogBll.Insert(workOrderLogEntity);
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    #endregion
                    string backUrl = UserLoginInfo.FilterBackUrl(PageHelper.GetPrePageUrl(this.Page));
                    PageHelper.ShowMessage(this.Page, String.Format("执行操作 {0} 成功！工单状态由 {1} 更新为 {2} ！", workOrderOperationEntity.OPERATIONNAME, workOrderOperationEntity.CURRENTSTATUSNAME, workOrderOperationEntity.NEXTSTATUSNAME), backUrl);
                }
                else
                {
                    PageHelper.ShowMessage(this.Page, String.Format("执行操作 {0} 失败！", workOrderOperationEntity.OPERATIONNAME));
                }
            }
            catch (Exception ex)
            {
                
                    PageHelper.ShowMessage(this.Page, String.Format("执行操作 {0} 失败！{1}", workOrderOperationEntity.OPERATIONNAME, ex.Message));
            }
        }

    }
}
